<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>节点练习 - 添加节点</title>
</head>

<body>
  <style>
    .font-color {
      color: royalblue;
    }

    .background-color {
      background-color: yellowgreen;
    }
  </style>
  <div id="three" class="three">
    我是three内容
    <ul>
      <li>简简单单的早餐</li>
      <li>简简单单的午饭</li>
      <li>简简单单的晚饭</li>
      <li>1</li>
      <li>2</li>
    </ul>
  </div>

  <button onclick="btn_add_start()">首行添加节点</button>
  <button onclick="btn_add_two()">第二行添加节点</button>
  <button onclick="btn_add_end()">末尾添加节点</button>
  <hr />
  <button onclick="btn_add_tag()">末尾添加元素节点</button>
  <button onclick="btn_add_txt()">末尾添加文本节点</button>
  <button onclick="btn_add_com()">末尾添加组合元素</button>
  <button onclick="btn_add_type()">给第二个节点添加class属性</button>
  <hr />

  <button onclick="btn_move()">第三行节点与第二行节点交换</button>

  <script>
    //新建标签节点
    let para = document.createElement("li");
    //新建文本节点
    let txt = document.createTextNode("牛奶当早餐");
    //组合
    para.appendChild(txt);

    let x = document.getElementById("three").getElementsByTagName("ul")[0]; //拿到ul节点
    let y = x.getElementsByTagName("li"); //拿到li节点
    //列表首行添加节点
    const btn_add_start = () => {
      x.insertBefore(para, y[0]);
    };
    //列表第二行添加节点
    const btn_add_two = () => {
      x.insertBefore(para, y[1]);
    };

    //列表末尾添加节点
    const btn_add_end = () => {
      x.appendChild(para);
    };

    //添加元素节点,
    const btn_add_tag = () => {
      let li = document.createElement("li");
      x.appendChild(li);
    };
    //添加文本节点
    const btn_add_txt = () => {
      let moring = document.createTextNode("早上好");
      x.appendChild(moring);
    };
    //组合技：元素与文本结合
    const btn_add_com = () => {
      let li = document.createElement("li");
      let moring = document.createTextNode("早上好");
      li.appendChild(moring);
      x.appendChild(li);
    };

    //添加属性（class也行）节点
    const btn_add_type = () => {
      y[1].setAttribute("class", "font-color background-color");
    };

    //第三行节点与第二行节点交换
    const btn_move = () => {
      x.insertBefore(y[2], y[1]);
      
    };
  </script>
</body>

</html>